package com.example.administrator.bleapp;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.example.administrator.bleapp.adapter.BLELIstAdapter;
import com.vise.baseble.ViseBle;
import com.vise.baseble.callback.IBleCallback;
import com.vise.baseble.callback.IConnectCallback;
import com.vise.baseble.callback.scan.IScanCallback;
import com.vise.baseble.callback.scan.ScanCallback;
import com.vise.baseble.common.PropertyType;
import com.vise.baseble.core.BluetoothGattChannel;
import com.vise.baseble.core.DeviceMirror;
import com.vise.baseble.exception.BleException;
import com.vise.baseble.model.BluetoothLeDevice;
import com.vise.baseble.model.BluetoothLeDeviceStore;

import java.util.List;

public class MainActivity extends Activity {
    private Button btn_h, btn_zc;
    private RecyclerView listview1, listview2;
    private List<BluetoothLeDevice> listBle;
    private String APP_ONE_CONNECTION = "AA5504010106F00F";//app第一次通讯验证
    private String APP_TOO_CONNECTION = "AA5504010207F00F";//app第二次通讯验证
    private String BLE_ONE_CONNECTION = "AA55080201AFBECDAFF0F00F";//ble第一次通讯验证返回
    private String BLE_TOO_CONNECTION = "AA55080202ABCDEFAB1AF00F";//ble第二次通讯验证返回
    private String imei;
    private BLELIstAdapter blelIstAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_sousuo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DeviceListActivity.start(MainActivity.this);
            }
        });


        initView();
        try {
            TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(this.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            imei = telephonyManager.getDeviceId();
        } catch (Exception e) {
            e.printStackTrace();
            imei = "";
        }
        checkBluetoothPermission();
    }

    private void initView() {

        btn_h = findViewById(R.id.btn_h);//呼梯
        btn_zc = findViewById(R.id.btn_zc);//注册
        listview1 = findViewById(R.id.listview1);
        listview2 = findViewById(R.id.listview2);

        listview1.setLayoutManager(new LinearLayoutManager(getBaseContext()));
        blelIstAdapter = new BLELIstAdapter(null);
        listview1.setAdapter(blelIstAdapter);

    }

    //初始化蓝牙
    private void loginBle() {
        //蓝牙相关配置修改
        ViseBle.config()
                .setScanTimeout(-1)//扫描超时时间，这里设置为永久扫描
                .setConnectTimeout(10 * 1000)//连接超时时间
                .setOperateTimeout(5 * 1000)//设置数据操作超时时间
                .setConnectRetryCount(3)//设置连接失败重试次数
                .setConnectRetryInterval(1000)//设置连接失败重试间隔时间
                .setOperateRetryCount(3)//设置数据操作失败重试次数
                .setOperateRetryInterval(1000)//设置数据操作失败重试间隔时间
                .setMaxConnectCount(3);//设置最大连接设备数量
        //蓝牙信息初始化，
        ViseBle.getInstance().init(this);
    }

    //搜索蓝牙
    private void searchBle() {
        ViseBle.getInstance().startScan(new ScanCallback(new IScanCallback() {
            @Override
            public void onDeviceFound(BluetoothLeDevice bluetoothLeDeviceStore) {
                blelIstAdapter.setNewData(listBle);
            }

            @Override
            public void onScanFinish(BluetoothLeDeviceStore bluetoothLeDeviceStore) {
                Toast.makeText(MainActivity.this, "完成", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onScanTimeout() {

            }
        }));
    }

    //连接蓝牙
    private void concatenonBle(BluetoothLeDevice bluetoothLeDevice) {
        ViseBle.getInstance().connect(bluetoothLeDevice, new IConnectCallback() {
            @Override
            public void onConnectSuccess(DeviceMirror deviceMirror) {
//                sendBle();
            }

            @Override
            public void onConnectFailure(BleException exception) {

            }

            @Override
            public void onDisconnect(boolean isActive) {

            }
        });
    }

//    //发送数据
//    private void sendBle(DeviceMirror deviceMirror, byte[] data) {
//        BluetoothGattChannel bluetoothGattChannel = new BluetoothGattChannel.Builder()
//                .setBluetoothGatt(deviceMirror.getBluetoothGatt())
//                .setPropertyType(PropertyType.PROPERTY_WRITE)
//                .setServiceUUID(serviceUUID)
//                .setCharacteristicUUID(characteristicUUID)
//                .setDescriptorUUID(descriptorUUID)
//                .builder();
//        deviceMirror.bindChannel(new IBleCallback() {
//            @Override
//            public void onSuccess(byte[] data, BluetoothGattChannel bluetoothGattChannel, BluetoothLeDevice bluetoothLeDevice) {
//
//            }
//
//            @Override
//            public void onFailure(BleException exception) {
//
//            }
//        }, bluetoothGattChannel);
//        deviceMirror.writeData(data);
//    }

    int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;

    /*
 校验蓝牙权限
 */
    private void checkBluetoothPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            //校验是否已具有模糊定位权限
            if (ContextCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
            } else {
                //具有权限
                loginBle();
            }
        } else {
            //系统不高于6.0直接执行
            loginBle();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//同意权限
                loginBle();
            } else {
// 权限拒绝
            }
        }
    }
}
